/*
* @Description: axios基础封装
* @Author: yxm
* @Date: 2023-11-20
*/
import axios from 'axios'
import { ElMessage } from "element-plus";
import { useUserStore} from "@/stores/user";
import router from '@/router' // vue3中 useRouter不允许在setup之外使用

const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000
})
// axios拦截器
httpInstance.interceptors.request.use( config => {
    //1. 从Pinia获取token数据
    const userStore = useUserStore()
    const token = userStore.userInfo?.token //弹幕大哥说这里要加个？
    if (token){
        config.headers.Authorization = `Bearer ${token}`  //格式固定
    }
    //2. 安装后端要求拼接token数据
    return config
}, e => Promise.reject(e))

//axios响应式拦截器
httpInstance.interceptors.response.use( res => res.data, e => {
    const userStore = useUserStore()
    //统一错误提示
    ElMessage({
        type: 'warning', message: e.response.data.message
    })
    //401 token 失效处理
    //1. 清除本地用户数据
    if (e.response.status === 401){
        userStore.clearUserInfo()
        router.push('/login')
    }
    //2. 跳转到登录页
    return Promise.reject(e)
})
export default httpInstance